import React, {} from 'react';
import { Route, withRouter, Switch, } from 'react-router-dom';
import { Schedule, Icon, Flex, Tools,List,TextareaItem,Bubble} from 'weaver-mobile';
import { observer, inject } from 'mobx-react';
import { RouteLayout } from 'weaver-mobile-page';
import Detail from '../detail/index';
import Report from '../report/index';
const getLabel = Tools.getLabel;
const HEIGHT = 0.32* window.innerHeight;
const store = [
  'calendarStore',
  'viewWorkplanStore',
  'createStore'
];
@inject(...store)
@withRouter
@observer
class Footer extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      yuyinfirstMessage: false,
      key: '1',
      visible: false,
      selected: '',
      span: [4, 1],
      voiceORcreate: true,
      isStart: true,
      vHeight: 0,
      siriHeight: 60,
      isRun: false,
      valuestring: '',
      siristart: true,
      borderWidth: 1,
      isTextarea: false, //
    };
  }

  componentDidMount = () => {
    this.checkJsApi(this.setTimeVoiceCreate); // yesVoice判断是否有语音功能，存在可语音创建日程(绑定事件)

    // this.createWorkplan();
  }

  checkJsApi = (callback) => {
    const {setState} = this.props.calendarStore;
    window.em && window.em.checkJsApi({
      jsApiList: ['continueSpeech','stopVoice'], // 需要检测的js接口列表
      success: function(res) {
        setState({
          yesVoice:  res['checkResult']['continueSpeech'], // 判断是否有语音功能
          continueSpeech: res['checkResult']['continueSpeech'],
          stopVoice: res['checkResult']['stopVoice'],
        },callback);
      }
    })
  }

  setTimeVoiceCreate = () => {
    setTimeout(() => {
      this.createWorkplan();
    }, 500);
  }

  createWorkplan = () => {
    let createVoice = this.refs.createVoice;
    let BEGIN = 0;
    let END = 0;
    let timer = {};
    let SW9 = createVoice ? new window.SiriWave({
          container: this.refs.voiceSiri,
          autostart: false,
          amplitude: 0.2,
          style: 'ios9'
        }) : '';

    const speeching = () => {
      const {setState,voiceContent} = this.props.calendarStore;
      window.em && window.em.continueSpeech({'changeVoice':function (argument) {
          if(argument/10 > 1) {
            SW9.setAmplitude(1);
          }else{
            SW9.setAmplitude(argument/10);
          }
        },'continueSpeechend':function (argument) { // 录音结束调用
        },'onContinueSpeech':function (argument) {
          let currentStr = '';
          if(typeof(argument) === 'string'){ // ios
            currentStr = JSON.parse(argument)['result'] ? JSON.parse(argument)['result'] : '';
          }else{ // android
            currentStr = argument['result'] ? argument['result'] : '';
          }
          setState({voiceContent: voiceContent+currentStr});
        },'success':function (argument) {
          // alert('success')
          setState({voiceSuccess: true})
        },'fail':function (argument) {
          setState({voiceSuccess: false,siriVisible: 'none',orVoice: true})
        },'cancel':function (argument) {
        /* body... */
        },'complete':function (argument) {
        /* body... */
        }
      })
    }
    const stopvoice = () => {
      window.em && window.em.stopVoice({'success':function (argument) {
        },'fail':function (argument) {
        },'cancel':function (argument) {
        },'complete':function (argument) {
        }
      })
    }
    const fnStart = () => {
      BEGIN = new Date().getTime();
      const {vHeight,} = this.state;
      const {voiceSuccess,setState} = this.props.calendarStore;
      timer = setTimeout(() => {
        speeching();// 开始录音,防止录音不全
        voiceSuccess && setState({siriVisible: 'block'}); // 开始波纹图
        if(vHeight === HEIGHT) {
          voiceSuccess && SW9.start();
        }else{
          // 第一次进入避免直接页面获得焦点
          voiceSuccess ? this.setState({vHeight: HEIGHT,isTextarea: true,borderWidth: 0},SW9.start()) // 开启语音
                        : this.setState({vHeight: HEIGHT,isTextarea: true,borderWidth: 0});
        }
      }, 250);
    }
    const fnEnd = () => {
      const {} = this.state;
      const {voiceSuccess,setState,orVoice} = this.props.calendarStore;
      END = new Date().getTime();
      setState({orVoice: true});
      clearTimeout(timer);
      if(END-BEGIN < 250) {
        // 点击
        !orVoice && this.createBtn();
        !orVoice && setState({orVoice: false});
      }else{
        voiceSuccess && stopvoice();
        SW9.setAmplitude(0.1);
        SW9.stop();
        setState({siriVisible: 'none'}); // 结束波纹图
      }
    }
    if (createVoice) {
      createVoice.addEventListener('touchstart',fnStart,false);
      createVoice.addEventListener('touchend',fnEnd,false);
    }
  }

  getFooterLeft = () => {
    const { pathname } = this.props.location;
    let labelActive = '';
    if (pathname === '/calendar/myCalendar') {
      labelActive = 'active';
    } else {
      labelActive = '';
    }
    return (
      <div className={`${labelActive} left`} onClick={(e) => {this.clickMyWorkplan()}} >
        <Icon  type={'my-meeting'} size='sm' onClick={(e) => {}} />
        <div className='label'>{getLabel(18480,'我的日程')}</div>
      </div> 
    );
  }

  clickMyWorkplan = () => {
    const { pathname } = this.props.location;

    if (pathname === '/calendar/myCalendar') {

    } else {
      this.props.history.push('/calendar/myCalendar');
    }
  }
  
  getFooterRight = () => {
    const { pathname } = this.props.location;
    let labelActive = '';
    if (pathname === '/calendar/myCalendar/report') {
      labelActive = 'active';
    } else {
      labelActive = '';
    }
    return (
      <div className={`${ labelActive } right`} onClick={(e) => {this.clickReport()}} >
        <Icon  type={'blog-report-form'} size='sm' />
        <div className='label'>{getLabel('15101','报表')}</div>
      </div>
    );
  }

  cancelVoice = () => {
    const {setState} = this.props.calendarStore;
    this.setState({vHeight: 0,borderWidth: 1,siristart: false});
    setState({voiceContent: '',orVoice: false,});
  }

  submitVoice = () => {
    const { addByWord, setParams } = this.props.createStore;
    const { voiceContent,setState,semanticStatus, getSemanticUrlAndParam } = this.props.calendarStore;
    if(voiceContent && voiceContent !== ''&& voiceContent !== ' ') {
      setParams({voiceCreateLoading: true});
      if (!semanticStatus) {
        getSemanticUrlAndParam(voiceContent, this.freshCalendar);
      } else {
        addByWord(voiceContent,this.freshCalendar); // 根据语音创建日程
      }
      this.setState({vHeight: 0,borderWidth: 1,siristart: false,voiceContent: ''});
      setState({voiceContent: '',orVoice: false});
    }else{
      Bubble.error(getLabel(500282,'您没有说话'),1,{top: '80%'});
    }
  }

  freshCalendar = () => {
    const { setParams } = this.props.createStore;
    let { selectDate } = this.props.calendarStore;
    this.getCalendarInfo();
    this.getWorkplanDatasList(selectDate);
    setParams({voiceCreateLoading: false});
  }

  getCalendarInfo = (date) => {
    let type = '';
    const { pathname } = this.props.location;
    if (pathname.indexOf('myCalendar') > -1) {
      type = 'myCalendar';
    }
    if (pathname.indexOf('allCalendar') > -1) {
      type = 'allCalendar';
    }
    const { getMyWorkplanDatas, getAllWorkplanDatas, userID} = this.props.calendarStore;
    type === 'allCalendar' && getAllWorkplanDatas({selectDate: date, viewType: 3, isCalendar: '1'});
    type === 'myCalendar' && getMyWorkplanDatas({selectDate: date, viewType: 3, isCalendar: '1'});
    type !== 'myCalendar' && type !== 'allCalendar' && getMyWorkplanDatas({selectDate: date, viewType: 3, selectUser: userID, isCalendar: '1'});
  }

  getWorkplanDatasList = (date) => {
    const { getMyWorkplanDatas, getAllWorkplanDatas, userID, setState} = this.props.calendarStore;
    const {setParams} = this.props.createStore;
    const { pathname } = this.props.location;
    let type = '';
    if (pathname.indexOf('myCalendar') > -1) {
      type = 'myCalendar';
    }
    if (pathname.indexOf('allCalendar') > -1) {
      type = 'allCalendar';
    }
    setState({selectDate: date});
    setParams({selectDate: date});
    localStorage && localStorage.setItem('selectDate', date);
    type === 'allCalendar' && getAllWorkplanDatas({selectDate: date, viewType: 1, isCalendar: '0'});
    type === 'myCalendar' && getMyWorkplanDatas({selectDate: date, viewType: 1, isCalendar: '0'});
    type !== 'myCalendar' && type !== 'allCalendar' && getMyWorkplanDatas({selectDate: date, viewType: 1, selectUser: userID, isCalendar: '0'});
  }

  clickReport = () => {
    const { pathname } = this.props.location;
    if (pathname === '/calendar/appointhrm/schdule') {
      this.props.history.push('/calendar/allCalendar/report');
    } else {
      this.props.history.push('/calendar/myCalendar/report');
    }
  }

  createBtn = (e) => {
    const { setParams } = this.props.createStore;
    const { pathname } = this.props.location;
    setParams({isEdit: false,createDisabled: false})
    if (pathname.indexOf('myCalendar') > -1 || pathname.indexOf('allCalendar') > -1 || pathname.indexOf('appointhrm') > -1 ) {
      this.props.history.push(`${ pathname }/create`);

    } else {
      this.props.history.push('/calendar/myCalendar/create');
    }
    return false;
  }

  changeVoiceStr = (v) => {
    const {setState} = this.props.calendarStore;
    setState({voiceContent: v})
  }

  reportList = () => {
    return [
      {
        key: 'oneWeekWorkplan',
        name: getLabel('503461','一周日程安排') 
      },
    ];
  }

  getZindex = () => {
    // 在他人日程语音创建日程需要提升层级
    const { pathname } = this.props.location;
    let style = {};
    if (pathname === '/calendar/appointhrm/schdule' || pathname === '/calendar/subordinate/schdule'
      || pathname === '/calendar/myCalendar/report/oneWeekWorkplan'|| pathname === '/calendar/myFllow/schdule'
    ) {
      style = { zIndex: 999 };
    }
    return style;
  }

  getLoading = () => {
    return (
      <div className='loaidng-icon' key='loading'>
        <Icon type='loading' size='lg'/>
      </div>
    );
  }

  render () {
    let { selectDate,weekStart,voiceContent,yesVoice,siriVisible,orVoice,isInit,semanticStatus,itemCardHeight} = this.props.calendarStore;
    const { voiceCreateLoading } = this.props.createStore;
    const { vHeight,borderWidth,isTextarea,yuyinfirstMessage, } = this.state;
    let maskHeight = vHeight === HEIGHT ? window.innerHeight-HEIGHT-50*window.getThemeVars()['hd'] : 0;
    // let voiceSiriHeight = 0.46*HEIGHT;
    yesVoice = yesVoice;
    
    return (
      <div className={'layout-footer'} style={ this.getZindex() }>
        { // 仅新建功能
          !yesVoice && <div className={'shedule-footer'} ref='sheduleFooter' style={{Zindex: 900,WebkitUserSelect: 'none'}}>
            <Flex className="workplan-footer" justify='start'>
              <Flex.Item className="workplan-footer-myworkplan" >
                {this.getFooterLeft()}
              </Flex.Item>
              <Flex.Item className="workplan-footer-create" >
                {<div className='icon create'><Icon  type={'blog-gengduo'} size='lg' onClick={(e) => {this.createBtn(e)}} /></div> }
              </Flex.Item>
              <Flex.Item className="workplan-footer-report" >
                {this.getFooterRight()}
              </Flex.Item>
            </Flex>
          </div>}

        {vHeight === HEIGHT && <div className='voiceMask' style={{height: maskHeight}} onClick={() => {this.cancelVoice()}}></div>}
        {yesVoice && <div className='voice-area' ref='voiceArea' style={{height: vHeight, zIndex: vHeight===0?'':999, display: vHeight===0?'none':'block'}}>
          <div className='voiceText'>
            {isTextarea && <List>
              <TextareaItem
                value={voiceContent}
                placeholder={getLabel(500283,"请按住说话")}
                onChange={v => this.changeVoiceStr(v)}
                rows={3}
              />
            </List>}
          </div>
          <div className='voiceSiriArea'>
            {<div className='voiceSiri' ref='voiceSiri' style={{display: siriVisible, width: window.innerWidth}}></div>}
          </div>
        </div>}
        {/*  */}
        {yesVoice && yuyinfirstMessage && <div className='firstMessage'>
            <div className='aaa'></div>
            <div>{getLabel(500284,'长按语音输入哦')}</div>
            <div className='arrow'></div>
          </div>}
        {yesVoice && <div className={'shedule-footer'} style={{WebkitUserSelect: 'none', borderTopWidth: borderWidth}}>
          <Flex className="workplan-footer" justify='start'>
            <Flex.Item className="workplan-footer-myworkplan" >
              {vHeight === HEIGHT &&<div className='voiceButton voiceButton-left' onClick={() => this.cancelVoice()}>{getLabel(386789,'取消')}</div>}
              {vHeight != HEIGHT && this.getFooterLeft()}
            </Flex.Item>
            <Flex.Item className="workplan-footer-create" >
              <div className='icon create' ref='createVoice'>
                {!orVoice && <Icon  type={'add-voice'} size='lg' />}
                {orVoice && <div className='icon icon-voice'><Icon type={'voice-1'} color='#fff' size='md' onClick={() => {}} /></div>}
              </div>
            </Flex.Item>
            <Flex.Item className="workplan-footer-report">
              {vHeight === HEIGHT &&<div className='voiceButton voiceButton-right' onClick={() => this.submitVoice()}>{getLabel(386788,'确定')}</div>}
              {vHeight != HEIGHT && this.getFooterRight()}
            </Flex.Item>
          </Flex>
        </div>}

        {voiceCreateLoading && this.getLoading()}
      </div>
    );
  }
}

export default Footer;